/**
 * 小程序后台接口
 * @description:
 * @author: junyong.hong
 * @createTime: 2019/11/3
 * @version: 1.0.0.0
 * @history:
 *    1、
 *    2、
 *
 */
let express = require('express')
let router = express.Router()
let request = require('request')
let config = require('./config')
config = Object.assign({}, config.mp)
let util = require('./../../util/util')
let dao = require('./../common/db')
let wxpay = require('./../common/wxpay')

// 获取session接口
router.get('/getSession', function (req, res) {
    let code = req.query.code
    // console.log('code', code)
    if (!code) {
        res.json(util.handleFail('code不能为空', 10001))
    } else {
        let sessionUrl = `https://api.weixin.qq.com/sns/jscode2session?appid=${config.appId}&secret=${config.appSecret}&js_code=${code}&grant_type=authorization_code`
        // console.log('sessionUrl', sessionUrl)
        request(sessionUrl, function (err, response, body) {
            let result = util.handleResponse(err, response, body)
            res.json(result)
        })
    }
})

// 小程序授权（用户写入数据库）
router.get('/login', async function (req, res) {

    // {"nickName":"洪俊勇","gender":1,"language":"zh_CN","city":"Quanzhou","province":"Fujian","country":"China","avatarUrl":"https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTL489bKbicqZdrbb1sCkeCGXKMiaFY6I1zEjgzXVoeR2a4X8OxBZxvFwJ7XGvGW39CMnI0o3IwT0ia3A/132"}
    let userInfo = JSON.parse(req.query.userInfo)
    // console.log('userInfo', userInfo)

    if (!userInfo) {
        res.json(util.handleFail('用户信息不能为空', 10002))
    } else {
        // 查询当前用户是否已经注册
        let userRes = await dao.query({ openid: userInfo.openid}, 'users_mp')
        if (userRes.code == 0) {
            if (userRes.data.length > 0) {  // 老用户
                res.json(util.handleSuc({
                    userId: userRes.data[0]._id
                }))
            } else {    // 新用户
                let insertData = await dao.insert(userInfo, 'users_mp')
                if (insertData.code == 0) {
                    let result = await dao.query({ openid: userInfo.openid}, 'users_mp')
                    res.json(util.handleSuc({
                        userId: result.data[0]._id
                    }))
                } else {
                    res.json(insertData)
                }
            }
        } else {
            res.json(userRes)
        }
    }
})

// 支付回调通知
router.get('/pay/callback', async function (req, res){
    res.json(util.handleSuc())
})

// 小程序支付
// http://localhost:3301/api/mp/pay/payWallet?money=100&openId=osO495cyzh43Z5A7GU9tQxtVr7NE
router.get('/pay/payWallet', function (req, res) {
    let openId = req.query.openId   // 用户的openid
    let appId = config.appId   // 小程序ID（应用的id）
    let attach = '小程序支付课程体验'    // 附加数据
    let body = '欢迎学习慕课网首门支付专项课程'    // 支付主体内容
    let total_fee = req.query.money // 支付总金额

    // 通知地址：异步接收微信支付结果通知的回调地址，通知url必须为外网访问的url，不能携带参数
    let notify_url = 'http://localhost:3301/api/mp/pay/callback'

    // 线上
    // let notify_url = 'myoli.xin/pay/api/mp/pay/callback'

    // ip = spbill_create_ip = 终端ip：支持IPV4和IPV6两种格式的IP地址，调用微信支付API的机器IP
    let ip = '192.168.1.164'    // 本机ip地址

    wxpay.order(appId, attach, body, openId, total_fee, notify_url, ip).then((result) => {
        res.json(util.handleSuc(result))
    }).catch((result) => {
        res.json(util.handleFail(result))
    })
})

module.exports = router







